package com.education.admin.modules.order.service.impl;

import com.education.admin.modules.order.entity.OrderInfo;
import com.education.admin.modules.order.mapper.OrderMapper;
import com.education.admin.modules.order.service.OrderService;
import com.education.admin.modules.student.mapper.StudentMapper;
import com.education.admin.modules.student.entity.Student;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单服务实现类
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public Map<String, Object> getStudentOrders(Integer pageNum, Integer pageSize) {
        try {
            // 获取当前学生ID
            Long studentId = getCurrentStudentId();
            log.info("Getting orders for studentId: {}", studentId);

            // 计算偏移量
            int offset = (pageNum - 1) * pageSize;

            // 查询订单列表
            List<Map<String, Object>> orders = orderMapper.getStudentOrders(studentId, pageSize, offset);

            // 处理订单状态文本
            for (Map<String, Object> order : orders) {
                Integer orderStatus = (Integer) order.get("orderStatus");
                order.put("orderStatusText", getOrderStatusText(orderStatus));

                Integer paymentStatus = (Integer) order.get("paymentStatus");
                order.put("paymentStatusText", getPaymentStatusText(paymentStatus));
            }

            // 统计总数
            int total = orderMapper.countStudentOrders(studentId);

            Map<String, Object> result = new HashMap<>();
            result.put("orders", orders);
            result.put("total", total);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("totalPages", (int) Math.ceil((double) total / pageSize));

            return result;
        } catch (Exception e) {
            log.error("Error getting student orders", e);
            throw new RuntimeException("获取订单列表失败", e);
        }
    }

    @Override
    public OrderInfo getOrderByNo(String orderNo) {
        return orderMapper.getOrderByNo(orderNo);
    }

    @Override
    public OrderInfo getOrderById(Long id) {
        return orderMapper.getOrderById(id);
    }

    @Override
    public OrderInfo createOrder(OrderInfo orderInfo) {
        // 生成订单号
        String orderNo = generateOrderNo();
        orderInfo.setOrderNo(orderNo);

        // 设置默认值
        if (orderInfo.getOrderStatus() == null) {
            orderInfo.setOrderStatus(1); // 默认待支付
        }
        if (orderInfo.getPaymentStatus() == null) {
            orderInfo.setPaymentStatus(0); // 默认未支付
        }
        if (orderInfo.getOrderSource() == null) {
            orderInfo.setOrderSource("miniprogram");
        }

        orderMapper.insertOrder(orderInfo);
        return orderInfo;
    }

    @Override
    public boolean updateOrderStatus(Long id, Integer orderStatus, Integer paymentStatus) {
        return orderMapper.updateOrderStatus(id, orderStatus, paymentStatus) > 0;
    }

    @Override
    public boolean cancelOrder(Long id, String cancelReason) {
        return orderMapper.cancelOrder(id, cancelReason) > 0;
    }

    /**
     * 获取当前学生ID
     */
    private Long getCurrentStudentId() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                String phone = request.getHeader("X-User-Phone");
                log.info("Getting student ID for phone: {}", phone);
                
                if (phone != null && !phone.isEmpty()) {
                    Student student = studentMapper.findByPhone(phone);
                    if (student != null) {
                        Long studentId = student.getId();
                        log.info("Found studentId: {} for phone: {}", studentId, phone);
                        return studentId;
                    }
                }
            }
            throw new RuntimeException("无法获取学生信息");
        } catch (Exception e) {
            log.error("Error getting current student ID", e);
            throw new RuntimeException("获取学生信息失败", e);
        }
    }

    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        return "ORD" + System.currentTimeMillis() + String.format("%04d", (int)(Math.random() * 10000));
    }

    /**
     * 获取订单状态文本
     */
    private String getOrderStatusText(Integer orderStatus) {
        if (orderStatus == null) return "未知";
        switch (orderStatus) {
            case 1: return "待付款";
            case 2: return "已支付";
            case 3: return "已完成";
            case 4: return "已取消";
            case 5: return "已退款";
            default: return "未知";
        }
    }

    /**
     * 获取支付状态文本
     */
    private String getPaymentStatusText(Integer paymentStatus) {
        if (paymentStatus == null) return "未知";
        switch (paymentStatus) {
            case 0: return "未支付";
            case 1: return "已支付";
            case 2: return "部分退款";
            case 3: return "全额退款";
            default: return "未知";
        }
    }
}
